﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;
using Microsoft.Expression.Encoder.ScreenCapture;
using System.Xml;
using System.IO;



namespace Profari_Heldur_Utan_Um_Prof
{
    public partial class TakeTask : Form
    {
        //Code to connect to the SQL
        #region SQL connection
        private static SqlConnection con = new SqlConnection("Data Source=orninn.com;Initial Catalog=Notendaprofanir;Persist Security Info=True;User ID=SonjaNew;Password=Léttjógúrt");
        private static DataTable dt = new DataTable();
        private static SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Project", con);
        private static DataSet ds = new DataSet();
        SqlDataReader r = null;
        #endregion

        #region Variables
        string filename;
        int recordingID;
        int bloodPressureID;
        int userID;
        string email;
        int countHelpPressed = 1;
        int evalID = StartChooseProject.globalevaluationID;
        string systolicValue;
        string diastolicValue;
        string pulseValue;
        private XmlDocument lastMeasurement = new XmlDocument();
        //ScreenCaptureJob job = new ScreenCaptureJob();
        ScreenCaptureJob job = new ScreenCaptureJob();
        #endregion

        public TakeTask()
        {
            int width = this.Size.Width;
            int height = this.Size.Height;
            job.OutputPath = @"c:\output";
            job.ShowFlashingBoundary = false;
            job.CaptureRectangle = new Rectangle(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            job.Start();
            InitializeComponent();
            try
            {
                lastMeasurement.Load("dinamap.xml");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not load reference XML file: " + ex.ToString());
            }

            lblHelp.Hide();
            lblEmail.Hide();
            Change();
            
            this.StartPosition = FormStartPosition.CenterScreen;
            formFullScreen();
        }

        private void Change()
        {
            getTaskInfo();
            getUrl();
            getEmail();
            getUser();
            getBlood();
            getRecording();
        }

        //Code to make the Form fullscreen
        private void formFullScreen()
        {
            this.WindowState = FormWindowState.Maximized;
            this.FormBorderStyle = FormBorderStyle.None;
        }

        private void getFileName()
        {
            var directory = new DirectoryInfo("C:\\output");
            var myFile = (from f in directory.GetFiles()
            orderby f.LastWriteTime descending
            select f).First();
            filename = myFile.Name;
        }
        //Code for SQL commands
        #region Sql Commands
        private void getTaskInfo()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT taskDescription FROM Task WHERE id = " + StartTask.ids[StartTask.counter], con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    lblHelp.Text = r.GetString(0);
                    return;
                }
            }

            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }
        private void getUrl()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT url FROM Evaluation WHERE id = " + evalID, con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    string url = r.GetString(0);
                    lblWebUrl.Text = url;
                    webBrowser1.Navigate(url);
                }
            }

            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }
        private void getEmail()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT email FROM Evaluation WHERE id = " + evalID, con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    if (!r.IsDBNull(0))
                    {
                        string mail = r.GetString(0);
                        lblEmail.Text = "Send an email to this address: " + Environment.NewLine + mail.ToString();
                        lblEmail.Show();
                    }
                    else
                    {
                       
                        lblEmail.Hide();
                    }
                    return;
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }
        private void getUser()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT TOP 1 id FROM UserInfo ORDER BY id desc", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    userID = r.GetInt32(0);
                    return;
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }
        private void getBlood()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT TOP 1 id FROM BloodPressure ORDER BY id desc", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    bloodPressureID = r.GetInt32(0);
                    return;
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }
        private void getRecording()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT TOP 1 id FROM Recording ORDER BY id desc", con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    recordingID = r.GetInt32(0);
                    return;
                }
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }

        //This SQL command is never used
        private void getUserFeedback()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT UFQ.isEssay, UFQ.isQuestion FROM UserFeedbackQuestion UFQ INNER JOIN UserFeedback UF ON UFQ.UserFeedbackID = UF.id INNER JOIN GroupEvaluations GE ON UFQ.UserFeedbackID = UF.id AND GE.groupsID = " + StartChooseProject.globalgroupsID + " AND GE.evaluationID = " + StartChooseProject.globalevaluationID , con);
                r = cmd.ExecuteReader();
                while (r.Read())
                {
                    /*
                    if (r.GetBoolean(0) == true)
                    {
                        System.Threading.Thread OpenEssay = new System.Threading.Thread(new System.Threading.ThreadStart(openEssay));
                        OpenEssay.SetApartmentState(System.Threading.ApartmentState.STA);
                        OpenEssay.Start();
                        this.Close();
                    }
                    else if (r.GetBoolean(1) == true)
                    {
                        System.Threading.Thread OpenSurvey = new System.Threading.Thread(new System.Threading.ThreadStart(openSurvey));
                        OpenSurvey.SetApartmentState(System.Threading.ApartmentState.STA);
                        OpenSurvey.Start();
                        this.Close();
                    }
                    else
                    {
                     * */
                        MessageBox.Show("Thank you for participating in this evaluation");
                        Application.Exit();
                    
                }
            }

            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                    con.Close();
            }
        }


        private void insertIntoFinish()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO TaskUser(taskID, userInfoID, recordingID, bloodPressureID, sortButtons) VALUES(" + StartTask.ids[StartTask.counter] + " ," + userID + " ," + recordingID + " ," + bloodPressureID + "  , 3)", con);
                cmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void insertIntoAbort()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO TaskUser(taskID, userInfoID, recordingID, bloodPressureID, sortButtons) VALUES(" + StartTask.ids[StartTask.counter] + " ," + userID + " ," + recordingID + " ," + bloodPressureID + "  , 1)", con);   
                cmd.ExecuteNonQuery();

            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());

            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }

        private void insertIntoBloodPressure()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO BloodPressure(diastolic, systolic, pressure) VALUES("
                    + diastolicValue + " ," + systolicValue + " ," + pulseValue + ")", con);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                {

                    con.Close();
                }
            }

        }
        private void insertIntoRecording()
        {

            getFileName();
            try
            {
                string path = "C:\\output\\" + filename;
                con.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO Recording(recording, recordingTime, commentID) VALUES('" + path + "' , '00:00:00.0' , 1)", con);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                Console.WriteLine("Error: {0}", ex.ToString());
            }
            finally
            {
                if (con != null)
                {
                    con.Close();
                }
            }
        }
        #endregion

        //Code for the buttons in this form
        #region Buttons
        private void btnAbortTask_Click(object sender, EventArgs e)
        {
            DialogResult abortTask = MessageBox.Show("Are you sure you want to skip this task?", "Quit", MessageBoxButtons.YesNo);
            if (abortTask == DialogResult.Yes)
            {
                job.Stop();
                insertIntoRecording();
                StartTask.i++;
                insertIntoAbort();
                StartTask.counter++;
                if (StartTask.length <= StartTask.counter)
                {
                    MessageBox.Show("Thank you for participating in this evaluation");
                    Application.Exit();
                }
                else
                {
                    StartTask.length = 0;
                    System.Threading.Thread OpenStartTask = new System.Threading.Thread(new System.Threading.ThreadStart(openStartTask));
                    OpenStartTask.SetApartmentState(System.Threading.ApartmentState.STA);
                    OpenStartTask.Start();
                    this.Close();
                }
            }  
        }
        private void btnTaskFinish_Click(object sender, EventArgs e)
        {

            job.Stop();
            insertIntoRecording();
            insertIntoFinish();
            StartTask.counter++;
            StartTask.i++;
            if (StartTask.length <= StartTask.counter)
            {
                //getUserFeedback();
                MessageBox.Show("Thank you for participating in this evaluation");
                Application.Exit();
                
            }
            else
            {
                StartTask.length = 0;
                System.Threading.Thread OpenStartTask = new System.Threading.Thread(new System.Threading.ThreadStart(openStartTask));
                OpenStartTask.SetApartmentState(System.Threading.ApartmentState.STA);
                OpenStartTask.Start();
                this.Close();
                
                measureTimer.Stop(); //Stops the timer
            }
            
        }
        private void btnHelp_Click(object sender, EventArgs e)
        {
            if (countHelpPressed % 2 == 0)
            {
                lblEmail.Hide();
                lblHelp.Hide();
                countHelpPressed++;
            }
            else if (countHelpPressed % 2 == 1)
            {
                getEmail();
                lblHelp.Show();
                countHelpPressed++;
            }

        }
        private void btnBack_Click_1(object sender, EventArgs e)
        {
            webBrowser1.GoBack();
        }
        private void btnForward_Click_1(object sender, EventArgs e)
        {
            webBrowser1.GoForward();
        }
        #endregion

        //The Open forms functions makes it able to move between forms and close the first form when the second one is opened
        #region OpenForms
        private void openStartTask()
        {
            Application.Run(new StartTask());
        }
        private void openSurvey()
        {
            Application.Run(new Survey());
        }
        private void openEssay()
        {
            Application.Run(new Essay());
        }
        #endregion

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser1.CanGoBack)
            {
                btnBack.Enabled = true;
            }
            else
            {
                btnBack.Enabled = false;
            }
            if (webBrowser1.CanGoForward)
            {
                btnForward.Enabled = true;
            }
            else
            {
                btnForward.Enabled = false;
            }
        }

        /*
         * The following functions are taken from 
         * the DinaMap program that is available 
         * on this website:http://code.google.com/p/dinamap/source/browse/#svn%2Ftrunk%2FDinamapN
        */
        #region Functions and ideas taken from DinaMap program

        //When form is load the program begins to get the timer to start
        private void TakeTask_Load(object sender, EventArgs e)
        {
            lblTime.Hide();
            clockTimer.Start();

            //The following code and comments are from the DinaMap program
            int interval = 30000; //Set time interval to measurements (10 seconds)
            measureTimer.Enabled = true; //Enable timer
            measureTimer.Interval = interval; //Assign interval to timer
            measureTimer.Start(); //Begin timer

        }

        //The following code was modified from the code that is used in the DinaMap program
        //Some of the comments are from the DinaMap program as well
        private void measureTimer_Tick(object sender, EventArgs e)
        {
            XmlDocument currentMeasurement = new XmlDocument();
            var s = "";
            Hashtable r = responseToHash(BloodPressureTool.Dina_GetStateOn());
            //variable s gets the values from the DinaMap blood pressure monitor
            foreach (string k in r.Keys)
            {
                s += String.Format("{0}: {1}", k, r[k]);
            }

            currentMeasurement = BloodPressureTool.Dina_GetStateOn();
            
            //If pulled measurement is not the same as the last one, handle it
            if (currentMeasurement.InnerText != lastMeasurement.InnerText && currentMeasurement != null && lastMeasurement != null)
            {                                          
                if (r.Count != 0)
                {
                    //Puts the value from the blood pressure monitor into the database
                    systolicValue = r["Systolic_blood_pressure_Value"].ToString();
                    diastolicValue = r["Diastolic_blood_pressure_Value"].ToString();
                    pulseValue = r["Pulse_Value"].ToString();

                    insertIntoBloodPressure();
                }
                
               
                this.handleResponse(); 
            }

        }

        //The following code and comments are from the DinaMap program
        //When a new measurement is found...
        private void handleResponse()
        {
            Hashtable h = new Hashtable();
            lastMeasurement = BloodPressureTool.Dina_GetStateOn();

            h = responseToHash(lastMeasurement);
        }


        //The following code and comments are from the DinaMap program
        // Build hash from XML data
        private Hashtable responseToHash(XmlDocument doc)
        {
            Hashtable h = new Hashtable();

            XmlNodeList doc_results = doc.GetElementsByTagName("Result");

            foreach (XmlNode pnode in doc_results)
            {
                foreach (XmlNode cnode in pnode.ChildNodes)
                {
                    if (cnode.Name == "Units")
                    {
                        h.Add(pnode.Attributes["name"].InnerText + "_" + cnode.Name, cnode.Attributes["name"].InnerText);
                    }
                    else if (cnode.Name == "Time_stamp")
                    {
                        DateTime d = new DateTime(
                            Convert.ToInt32(cnode.Attributes["year"].InnerText),
                            Convert.ToInt32(cnode.Attributes["month"].InnerText),
                            Convert.ToInt32(cnode.Attributes["day"].InnerText),
                            Convert.ToInt32(cnode.Attributes["hour"].InnerText),
                            Convert.ToInt32(cnode.Attributes["minute"].InnerText),
                            Convert.ToInt32(cnode.Attributes["second"].InnerText));

                        h.Add(pnode.Attributes["name"].InnerText + "_" + cnode.Name, d);
                    }
                    else
                        h.Add(pnode.Attributes["name"].InnerText + "_" + cnode.Name, cnode.InnerText);
                }
            }

            return h;
        }

        private void clockTimer_Tick(object sender, EventArgs e)
        {
            //The following code and comments are from the DinaMap program
            // Every time timer is called by system...
            string szHour;
            szHour = DateTime.Now.ToString("h:mm:ss");
            lblTime.ForeColor = Color.Black;
            lblTime.Text = szHour;
        }

        #endregion
    }
}
